package com.topcent.tioxyc.xxljob;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.DeliveryDocumentsMapper;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.DeliveryDocuments;
import com.topcent.tioxyc.pojo.SalesOrder;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * @author: weidian
 * @date: 2024/10/28 15:30
 * @Description:
 */
@Slf4j
@Component
public class YY1_KPI {

    @Autowired
    private Yy1KpiMapper yy1KpiMapper;
    @Autowired
    private DeliveryDocumentsMapper deliveryDocumentsMapper;

    @XxlJob("YY1_KPI")
    public void YY_KPl(){
        Header[] headers = new Header[3];
        headers[0] = new BasicHeader("Accept", "application/json");
        headers[1] = new BasicHeader("Authorization", "Basic " + KeyConstant.SAP01);
        headers[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_SALESBOARD_CDS/YY1_SalesBoard", headers, null);
        String d = entries.getStr("d");
        JSONObject objects = JSONUtil.parseObj(d);
        String results = objects.getStr("results");
        JSONArray objectss = JSONUtil.parseArray(results);
        List<com.topcent.tioxyc.pojo.YY1_KPI> yy1Kpis = JSONUtil.toList(objectss, com.topcent.tioxyc.pojo.YY1_KPI.class);

        // 遍历并删除符合条件的对象
        /*Iterator<com.topcent.tioxyc.pojo.YY1_KPI> iterator = yy1Kpis.iterator();
        while (iterator.hasNext()) {
            com.topcent.tioxyc.pojo.YY1_KPI doc = iterator.next();
            // 检查字段是否符合条件
            // 检查 getPurchaseOrderByCustomer 是否包含 "AB008"
            //boolean containsAB008 = doc.getPurchaseOrderByCustomer() != null && doc.getPurchaseOrderByCustomer().contains("AB008");
            // 删除条件：getSalesDocApprovalStatusDesc 不是 "已审批" 或 getPurchaseOrderByCustomer 包含 "AB008" || containsAB008
            if (!"已审批".equals(doc.getSalesDocApprovalStatusDesc())) {
                iterator.remove();
            }
        }*/

        // 获取最早审核日期
        Map<String, DateTime> salesDocMinDateMap = this.getSalesOrderList().stream()
                .filter(so -> so.getReview_date() != null) // 过滤空日期
                .collect(Collectors.toMap(
                        SalesOrder::get_widget_1718759603973, // 键：销售单号
                        SalesOrder::getReview_date,   // 值：日期
                        BinaryOperator.minBy(Comparator.naturalOrder()) // 冲突时保留较小的日期
                ));

        yy1KpiMapper.truncateTable();
        for (com.topcent.tioxyc.pojo.YY1_KPI yy1Kpi : yy1Kpis) {
            yy1Kpi.setYY1_oldestTime_SDH(Optional.ofNullable(salesDocMinDateMap.get(yy1Kpi.getSalesDocument())).map(DateTime::toLocalDateTime).orElse(null));

            yy1Kpi.setYY1_lachangedatetime1_SDHs(parseSapDate(yy1Kpi.getYY1_lachangedatetime1_SDH()));
            yy1Kpi.setCreationDates(parseSapDate(yy1Kpi.getCreationDate()));
            yy1Kpi.setYY1_lastapptime_SDHS(parseSapDate(yy1Kpi.getYY1_lastapptime_SDH()));
            yy1Kpi.setRequestedDeliveryDates(parseSapDate(yy1Kpi.getRequestedDeliveryDate()));

            String businessText = yy1Kpi.getBusinessPartnerGroupingText();
            if(StringUtils.isNotBlank(businessText)){
                int separatorIndex = businessText.indexOf("-");
                if (separatorIndex != -1) {
                    businessText = businessText.substring(0, separatorIndex);
                }
            }
            if(StringUtils.isNotBlank(yy1Kpi.getVCDescription()) && yy1Kpi.getVCDescription().contains("标准码:")){
                // 找到 "标准码:" 的起始位置
                int startIdx = yy1Kpi.getVCDescription().indexOf("标准码:") + "标准码:".length();

                // 找到第一个 ";" 的位置
                int endIdx = yy1Kpi.getVCDescription().indexOf(";", startIdx);

                // 截取标准码内容
                String standardCode = yy1Kpi.getVCDescription().substring(startIdx, endIdx);
                yy1Kpi.setYY1_KS_SD_SDI(standardCode);
            }
            yy1Kpi.setBusinessPartnerGroupingText(businessText);
            yy1Kpi.setGsjing(yy1Kpi.getNetAmount_1().multiply(yy1Kpi.getExchangeRate_b()));
            yy1Kpi.setGshan(yy1Kpi.getConditionAmount1().multiply(yy1Kpi.getExchangeRate_b()));

            int i1 = yy1KpiMapper.insertSalesDocument(yy1Kpi);
            if (i1 == 0) {
                log.info("YY1_KPl插入失败，ID为{}", yy1Kpi.getID());
            }
        }

        Header[] headers1 = new Header[3];
        headers1[0] = new BasicHeader("Accept", "application/json");
        headers1[1] = new BasicHeader("Authorization", "Basic " + KeyConstant.SAP01);
        headers1[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries1 = ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/YY1_DD1_API_CDS/YY1_DD1_API", headers1, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<DeliveryDocuments> deliveryDocuments = JSONUtil.toList(objectss1, DeliveryDocuments.class);

        deliveryDocumentsMapper.truncateTable();
        for (DeliveryDocuments deliveryDocuments1 : deliveryDocuments) {

            deliveryDocuments1.setCreationDates(parseSapDate(deliveryDocuments1.getCreationDate()));
            deliveryDocuments1.setDocumentDates(parseSapDate(deliveryDocuments1.getDocumentDate()));
            deliveryDocuments1.setActualGoodsMovementDates(parseSapDate(deliveryDocuments1.getActualGoodsMovementDate()));
            deliveryDocuments1.setPlannedGoodsIssueDates(parseSapDate(deliveryDocuments1.getPlannedGoodsIssueDate()));
            deliveryDocuments1.setCreationDate_1s(parseSapDate(deliveryDocuments1.getCreationDate_1()));

            switch (deliveryDocuments1.getBusinessPartnerGrouping()) {
                case "BPAB": deliveryDocuments1.setBusinessPartnerGrouping("法人供应商"); break;
                case "Z001": deliveryDocuments1.setBusinessPartnerGrouping("外部供应商"); break;
                case "Z002": deliveryDocuments1.setBusinessPartnerGrouping("贸易商"); break;
                case "Z003": deliveryDocuments1.setBusinessPartnerGrouping("应用商"); break;
                case "Z004": deliveryDocuments1.setBusinessPartnerGrouping("零售商"); break;
                case "Z005": deliveryDocuments1.setBusinessPartnerGrouping("员工供应商"); break;
                case "Z006": deliveryDocuments1.setBusinessPartnerGrouping("财务供应商"); break;
                default: deliveryDocuments1.setBusinessPartnerGrouping("未知分组"); break;
            }
            int i1 = deliveryDocumentsMapper.insertDeliveryDocument(deliveryDocuments1);
            if (i1 == 0) {
                log.info("DeliveryDocuments插入失败，ID为{}", deliveryDocuments1.getID());
            }

        }
    }

    private DateTime parseSapDate(String sapDateStr) {
        if (StringUtils.isNotBlank(sapDateStr)) {
            long timestamp = Long.parseLong(ConnmeUtils.extractTimestamp(sapDateStr));
            LocalDateTime ldt = ConnmeUtils.convertTimestampToLocalDateTime(timestamp);
            return new DateTime(ConnmeUtils.formatDateTime(ldt), DatePattern.NORM_DATETIME_FORMAT);
        }
        return null;
    }

    public List<SalesOrder> getSalesOrderList(){
        List<SalesOrder> salesOrderList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            salesOrderList.addAll(list);
        } while (fale);
        return salesOrderList;
    }

}
